<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" >
          <a-row :gutter="8">
            <a-col :md="8" :sm="24">
              <a-form-item label="字典字段" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select showSearch v-model="queryParam.dictField" placeholder="请选择" allowClear :filterOption="filterOption">
                  <a-select-option v-for="item in dictDataField.fieldData" :key="item.dictField" :value="item.dictField">{{ item.dictField }}-{{ item.fieldName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="字段名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.fieldName" placeholder="支持模糊查询"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.status" placeholder="请选择" allowClear >
                    <a-select-option value="0">禁用</a-select-option>
                    <a-select-option value="1">启用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="字典值" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.dictKey" placeholder="精确查找"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="字典名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.dictValue" placeholder="支持模糊查询"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="() =>{this.findDictListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="dictListTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        highlight-hover-column
        highlight-current-column
        highlight-cell
        height="400"
        size="small"
        :columns="tableColumn"
        row-id="sysId"
        :data="tableData"
        :loading="loading"
        :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
        :pager-config="tablePage"
        :checkbox-config="{reserve: true}"
        @page-change="handlePageChange"
      >
      </vxe-grid>
      <a-modal
        :title="modalTitle"
        centered
        style="top: 10px;"
        width="85%"
        destroyOnClose
        v-model="visible"
        @ok="saveDict"
        cancelText="关闭"
        okText="保存"
      >
        <dict-form ref="dictPage" :dictInfo="selectData" />
      </a-modal>
    </a-card>
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
      <a-tooltip placement="top" title="字典字段为空则清除全部数据字典缓存，有选择则清除单个缓存">
        <a-button style="margin-left: 8px" type="primary" icon="plus" @click="() =>{this.clearCahce()}">清除缓存</a-button>
      </a-tooltip>
      <a-button style="margin-left: 8px" type="primary" icon="plus" @click="() =>{this.addDict()}">新增字典</a-button>
      <a-button style="margin-left: 8px" type="primary" icon="plus" @click="() =>{this.copyDict()}">复制新增字典</a-button>
      <a-button style="margin-left: 8px;" type="primary" icon="edit" @click="() =>{this.editDict()}">编辑字典</a-button>
      <a-button style="margin-left: 8px" type="danger" icon="minus" @click="() =>{this.deleteDict()}">删除</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import { getDictList,getDictField,addDict,editDict,deleteBatchDict,clearCacheDict } from "@/services/system/api"
import FooterToolBar from '@/components/FooterToolbar'
import modal from 'ant-design-vue/es/modal'
import DictForm from '@/pages/system/form/DictForm'
import moment from 'moment'
const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'processing',
    text: '启用'
  }
}
const flagMap = {
  0: {
    status: 'default',
    text: '否'
  },
  1: {
    status: 'success',
    text: '是'
  }
}
export default {
  name: 'DictManager',
  components: {
    FooterToolBar,
    DictForm
  },
  data () {
    return {
      description: '数据字典管理',
      dictDataField: {},
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 20
      },
      tableColumn: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        { type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
        { field: 'sysId', title: '字典Id', fixed: 'left', visible: false, align: 'center', width: 150 },
        { field: 'dictField', title: '所属字段', align: 'center', fixed: 'left', width: 150 },
        { field: 'fieldName', title: '所属字段名称', align: 'center', width: 250 },
        { field: 'dictKey', title: '字典属性', align: 'center', width: 150 },
        { field: 'dictValue', title: '字典属性名称', align: 'center', width: 250 },
        { field: 'status', title: '状态', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatStatus(row.status)] } } },
        { field: 'fixed', title: '是否可编辑', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatflag(row.fixed)] } } },
        { field: 'classify', title: '所属分类', align: 'center', width: 150 },
        { field: 'parentField', title: '父字段', align: 'center', width: 150 },
        { field: 'parentFieldName', title: '父字段名称', align: 'center', width: 250 },
        { field: 'parentKey', title: '父字典属性', align: 'center', width: 150 },
        { field: 'parentDictValue', title: '父字典属性名称', align: 'center', width: 250 },
        { field: 'orderNo', title: '排序', align: 'center', width: 80 },
        { field: 'rate', title: '级别', align: 'center', width: 80 },
        { field: 'orgId', title: '所属组织编码ID', visible: false, align: 'center', width: 80 },
        { field: 'orgNumber', title: '所属组织编码', align: 'center', width: 80 },
        { field: 'orgName', title: '所属组织名称', align: 'center', width: 250 },
        { field: 'icon', title: '图标', align: 'center', width: 250 },
        { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 350 }
      ],
      tableData: [],
      modalTitle: '操作',
      selectData: {}
    }
  },
  created () {
    // 数据初始化
    // 数据字典初始化
    const params = {}
    this.$http.post(getDictField,params).then(res => {
      this.dictDataField = res.result
    })
    // 初始化组织列表
    this.findDictList()
  },
  methods: {
    moment,
    formatStatus (cellValue) {
      if (cellValue) {
        const text = statusMap[cellValue].text
        const status = statusMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    formatflag (cellValue) {
      if (cellValue) {
        const text = flagMap[cellValue].text
        const status = flagMap[cellValue].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageNum = currentPage
      this.tablePage.pageSize = pageSize
      this.findDictList()
    },
    findDictListBtn () {
      this.tablePage.currentPage = 1
      this.tablePage.pageNum = 1
      this.findDictList()
    },
    // 数据字典列表查询
    findDictList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      setTimeout(() => {
        this.$http.post(getDictList,params).then((res) => {
          const data = res.result.list
          this.tableData = data
          this.tablePage.total = res.result.total
          this.tablePage.currentPage = res.result.pageNum
          this.tablePage.pageNum = res.result.pageNum
          this.tablePage.pageSize = res.result.pageSize
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }, 20)
    },
    addDict () {
      this.modalTitle = '新增字典信息'
      this.selectData = {}
      this.visible = true
    },
    copyDict () {
      this.modalTitle = '复制新增字典信息'
      const thisChecked = this.$refs.dictListTable.getCheckboxRecords()
      if (!thisChecked) {
        modal.warn({ title: '提示', content: '请先选择需要复制的数据' })
        return
      }
      if (thisChecked.length === 1) {
        const dict = thisChecked[0]
        delete dict.sysId
        this.selectData = dict
        this.visible = true
      } else if (thisChecked.length === 0) {
        modal.warn({ title: '提示', content: '请先选择需要复制的数据' })
      } else {
        modal.warn({ title: '提示', content: '只能勾选一条数据复制' })
      }
    },
    editDict () {
      const thisChecked = this.$refs.dictListTable.getCheckboxRecords()
      if (!thisChecked) {
        modal.warn({ title: '提示', content: '请先选择需要修改的数据' })
        return
      }
      if (thisChecked.length === 1) {
        this.modalTitle = '修改字典信息'
        this.selectData = thisChecked[0]
        if (this.selectData.fixed === '0') {
          modal.warn({ title: '提示', content: '不可编辑数据不能修改' })
          return
        }
        this.visible = true
      } else if (thisChecked.length === 0) {
        modal.warn({ title: '提示', content: '请先选择需要修改的数据' })
      } else {
        modal.warn({ title: '提示', content: '只能勾选一条数据修改' })
      }
    },
    saveDict () {
      // 表单验证
      const { $refs: { dictPage } } = this
      const dictForm = new Promise((resolve, reject) => {
        dictPage.form.validateFields((err, values) => {
          if (err) {
            reject(err)
            return
          }
          resolve(values)
        })
      })
      this.errors = []
      Promise.all([dictForm]).then(values => {
        if (values && values.length > 0) {
          const dict = values[0]
          if (dict.sysId) {
            setTimeout(() => {
              this.$http.post(editDict,dict).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                this.visible = false
                const data = [...this.tableData]
                data.forEach((item, index, arr) => {
                  item.fieldName = res.result.fieldName
                  if (item.sysId === res.result.sysId) {
                    arr.splice(index, 1, res.result)
                  }
                })
                this.tableData = data
              }).catch(() => {
              })
            }, 20)
          } else {
            setTimeout(() => {
              this.$http.post(addDict,dict).then(() => {
                modal.info({ title: '成功提示', content: '新增成功' })
                this.visible = false
                const params = {}
                this.$http.post(getDictField,params).then(res => {
                  this.dictDataField = res.result
                })
                this.findDictList()
              }).catch(() => {
              })
            }, 20)
          }
          // 更新字段下拉
          this.$http.post(getDictField,{}).then(res => {
            this.dictDataField = res.result
          })
        }
      }).catch(() => {
        const errors = Object.assign({}, dictPage.form.getFieldsError())
        const tmp = { ...errors }
        this.errorList(tmp)
      })
    },
    errorList (errors) {
      if (!errors || errors.length === 0) {
        return
      }
      this.errors = Object.keys(errors)
        .filter(key => errors[key])
        .map(key => ({
          key: key,
          message: errors[key][0]
        }))
    },
    deleteDict () {
      const sysIds = []
      const selectReserveRecords = this.$refs.dictListTable.getCheckboxReserveRecords()
      if (selectReserveRecords && selectReserveRecords.length > 0) {
        selectReserveRecords.forEach((item) => {
          sysIds.push(item.sysId)
        })
      }
      const thisChecked = this.$refs.dictListTable.getCheckboxRecords()
      if (thisChecked && thisChecked.length > 0) {
        thisChecked.forEach((item) => {
          sysIds.push(item.sysId)
        })
      }
      if (sysIds.length > 0) {
        const params = {}
        params.sysIds = sysIds
        setTimeout(() => {
          this.$http.post(deleteBatchDict,params).then(() => {
            modal.info({ title: '成功提示', content: '删除字典成功' })
            this.findDictList()
          }).catch(() => {
          })
        }, 20)
      } else {
        modal.warn({ title: '提示', content: '请先选择需要删除的数据' })
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    clearCahce () {
      const params = {}
      params.dictField = this.queryParam.dictField
      setTimeout(() => {
        this.$http.post(clearCacheDict,params).then(() => {
          modal.info({ title: '成功提示', content: '清除成功' })
        }).catch(() => {
        })
      }, 20)
    },
    clearAll () {
      this.queryParam = {}
      this.findDictList()
      setTimeout(() => {
        this.$refs.dictListTable.clearSelection()
        this.$refs.dictListTable.clearSelectReserve()
      }, 50)
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
